package com.multysite.controller.admin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.NamespaceManager;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.multysite.entity.Category;
import com.multysite.entity.News;
import com.multysite.entity.Tag;
import com.multysite.model.CategoryModel;
import com.multysite.model.NewsModel;
import com.multysite.model.TagModel;
import com.multysite.util.Setting;
import com.multysite.util.StringHelper;

@SuppressWarnings("serial")
public class EditNewsServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(EditNewsServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			resp.setCharacterEncoding("utf-8");
			if (!NamespaceManager.get().equals(Setting.getGeneralNamespace())) {
				String alias = req.getParameter("alias");
				News obj = NewsModel.getById(alias);

				if (obj != null) {
					CategoryModel cateModel = new CategoryModel();
					cateModel.prepareAll();
					if (cateModel.getListResult().size() == 0) {
						List<Category> listCate = new ArrayList<Category>();
						Category cate = new Category();
						cate.setTitle("Uncategory");
						cate.setAlias("uncategory");
						cate.setLevel(1);
						cate.setParentAlias("");
						CategoryModel.insert(cate);
						listCate.add(cate);
						req.setAttribute("listCategory", listCate);
					} else {
						req.setAttribute("listCategory",
								cateModel.getListResult());
					}
					cateModel.prepareAllParrentList();
					req.setAttribute("listParentCategory",
							cateModel.getListResult());
					req.setAttribute("action", "edit");
					req.setAttribute("obj", obj);
					req.getRequestDispatcher("/admin/pages/news-form.jsp")
							.forward(req, resp);
				} else {
					resp.getWriter().println(
							"This News is not exits or has been deleted !");
				}
			} else {
				resp.getWriter().println("Invalid Url");
			}
		} catch (ServletException e) {
			e.printStackTrace();
			log.warning(e.toString());
			resp.sendError(4000,
					"Website is down for maintenance. We are sorry for the inconvenience !");
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		BlobstoreService blobService = BlobstoreServiceFactory
				.getBlobstoreService();
		ImagesService imageService = ImagesServiceFactory.getImagesService();
		try {
			String alias = req.getParameter("alias");
			News obj = NewsModel.getById(alias);
			if (obj != null) {
				String action = req.getParameter("action");
				String title = req.getParameter("title");
				String content = req.getParameter("content");
				String source = req.getParameter("source");
				String category = req.getParameter("category");
				String tags = req.getParameter("tags");
				if (action != null && action.equals("edit")) {
					obj.setTitle(title);
					obj.setAlias(StringHelper.replaceVietnamese(title));
					obj.setContent(content);
					obj.setSource(source);

					/*
					 * process thumb image
					 */
					try {
						Map<String, List<BlobKey>> blobs = blobService
								.getUploads(req);
						List<BlobKey> blobKeys = blobs.get("img");
						if (blobKeys != null && blobKeys.size() > 0) {
							for (BlobKey blobKey : blobKeys) {
								byte[] arr = blobService.fetchData(blobKey, 0,
										20);
								if (arr.length > 0) {
									obj.setThumb(imageService
											.getServingUrl(blobKey));
								}
							}
						}
					} catch (Exception e) {

					}

					/*
					 * process category
					 */
					Category cate = CategoryModel.getById(category);
					if (cate != null) {
						obj.setCategory(cate.getTitle());
						obj.setCategoryAlias(cate.getAlias());
					}
					/*
					 * process tag
					 */
					try {
						ArrayList<String> listTag = new ArrayList<String>();
						String[] splitTag = tags.split(",");
						for (String string : splitTag) {
							String tagAlias = StringHelper
									.replaceVietnamese(string.trim());
							Tag tag = TagModel.getById(tagAlias);
							if (tag != null) {
								List<News> listNews = tag.recoverListNews();
								for (int i = 0; i < listNews.size(); i++) {
									if (listNews.get(i).getAlias()
											.equals(obj.getAlias())) {
										listNews.remove(i);
									}
								}
								listNews.add(obj);
								tag.tranformListNews(listNews);
								TagModel.insert(tag);
							} else {
								tag = new Tag();
								tag.setAlias(tagAlias);
								tag.setTitle(string);
								List<News> listNews = new ArrayList<News>();
								listNews.add(obj);
								tag.tranformListNews(listNews);
								TagModel.insert(tag);
							}
							String objTag = tagAlias + "," + string;
							listTag.add(objTag);
						}
						obj.setTags(listTag);
					} catch (Exception e) {

					}
					NewsModel.insert(obj);
					resp.sendRedirect("/admin/news/edit?alias="
							+ obj.getAlias());
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.warning(e.toString());
			resp.sendError(4000,
					"Website is down for maintenance. We are sorry for the inconvenience !");
		}
	}
}
